<?php 

$ws = new swoole_websocket_server("0.0.0.0", 9501);


// $ws->set([
    
//     'enable_static_handler'=>true,
//     'document_root'=>"/www/wwwroot/ymh/root",
// ]);


//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
    $fd[] = $request->fd;
    $GLOBALS['fd'][] = $fd;
    echo "$request->fd 连接上了";
    
    $ws->push($request->fd, "hello, welcome\n");
});
    
    //监听WebSocket消息事件
    $ws->on('message', function ($ws, $frame) {
          $arr=[];
          $arr["fd"]=$frame->fd;
          $arr["data"]=$frame->data;
//           var_dump($arr);
          $arr=json_encode($arr);
          
          echo $arr;
         
        $msg=$frame->data;
//         var_dump($GLOBALS['fd']);
       
        //exit;
        foreach($GLOBALS['fd'] as $aa){
            foreach($aa as $i){
                
                $ws->push($i,$msg);
            }
        }
        // $ws->push($frame->fd, "server: {$frame->data}");
        // $ws->push($frame->fd, "server: {$frame->data}");
    });

//     $ws->on('message', function ($server, $frame) {
//         echo "\n";
//         echo "{$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
//         $arr=[];
//         $arr['context']=$frame->data;
//         $arr['id']=$frame->fd;
        
       
        
//         try
//         {
//             foreach($GLOBALS['fd'] as $item){
//                 foreach($item as $i){
//                     $ws->push($i,$frame->data);
//                 }
//             }
//         }
//         catch(Exception $e)
//         { 
//             echo "-------------------";
//             echo(date("Y-m-d",time()));
//             var_dump($GLOBALS['fd']);
            
//             $ws->push($frame->fd,$frame->data);
//         }
                    
//         });
        
        //监听WebSocket连接关闭事件
        $ws->on('close', function ($ws, $fd) {
            echo "{$fd} is 关闭 \n";
        });
            
            $ws->start();